import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

import net.miginfocom.swing.MigLayout;


/**
 * Main interface with which user can choose the image to transform
 * 
 * @author root
 * 
 */
@SuppressWarnings("serial")
public class Main extends JFrame {

	/**
	 * Button to chose an image
	 */
	private JButton upload = new JButton(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
	/**
	 * Start button
	 */
	private JButton start = new JButton("start");
	/**
	 * Path of the image selected
	 */
	private String sourcePath = "";

	/**
	 * Initialize user interface
	 */
	public Main() {
		// settaggi finestra
		super("Ascii Art");
		setLayout(new MigLayout());
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// settaggi upload
		upload.setBorder(null);
		upload.setContentAreaFilled(false);
		upload.setRolloverEnabled(true);
		upload.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon.jpg")));
		upload.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser chooser = new JFileChooser();
				chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

				chooser.getCurrentDirectory();

				int returnValue = chooser.showOpenDialog(upload);

				if (returnValue == JFileChooser.APPROVE_OPTION) {
					sourcePath = chooser.getSelectedFile().toString();

					ImageIcon tmp = new ImageIcon(sourcePath);
					// mostro la foto nella schemata java
					tmp.setImage(tmp.getImage().getScaledInstance(200, 180, Image.SCALE_AREA_AVERAGING));

					// file di destinazione

					upload.setIcon(tmp);
					Main.this.paintAll(Main.this.getGraphics());
				}
			}
		});

		add(upload, "wrap");

		start.setPreferredSize(new Dimension(200, 50));
		start.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (!sourcePath.equals(""))
					new GrayScale(sourcePath, Main.this);

			}
		});

		add(start, "gaptop 15");
		pack();
		paintAll(getGraphics());
	}

	/**
	 * Change the image of UPLOAD button ,so you can have a preview of the image selected
	 * 
	 * @param image
	 *           image selected
	 */
	public void changeIcon(ImageIcon image) {
		upload.setIcon(image);
		paintAll(getGraphics());
	}

	/**
	 * Main method
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		new Main();
	}

}
